package com.pinyougou.manager.controller;

import com.pinyougou.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class LoginController
{
    @PostMapping("/login")
    public String login(User user)
    {
        try
        {
            // 获得认证的主体
            Subject subject= SecurityUtils.getSubject();
            //创建用户名与密码令牌
            UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());
            //身份认证
            subject.login(token);
            //判断用户名是否通过身份认证
            if(subject.isAuthenticated())
            {
                return "redirect:/admin/index.html";
            }
        }
        catch (AuthenticationException e)
        {
            e.printStackTrace();
        }
        return "redirect:/login.html";
    }

    @GetMapping("/findLoginUser")
    @ResponseBody
    public String findLoginUser()
    {
        return SecurityUtils.getSubject().getPrincipal().toString();
    }

}